<template>
<div class="app-container">
  <header class="app-header">
    <span class="title">{{$route.meta.title}}</span>
    <el-button type="success" icon="el-icon-upload" @click.native="upLoadResources">上传资源</el-button>
    <el-button type="primary" icon="el-icon-document-add" @click.native="groupWare">合并资源</el-button>
    <el-button type="danger" icon="el-icon-delete" @click.native="allDelItem">批量删除</el-button>  
  </header>
  <el-form :inline="true" :model="listQuery" class="query-form">
    <el-form-item>
      <el-input v-model="listQuery.resName" :clearable = "true" placeholder="请输入资源名称"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button-group>
        <el-button type="primary" icon="el-icon-search"  @click="onSubmit(true)">查询</el-button>
        <el-button type="primary" icon="el-icon-refresh"  @click="onSubmit(false)">刷新</el-button>
      </el-button-group>
    </el-form-item>
  </el-form> 
  <el-table v-loading="loading" :data="list" border  @selection-change="handleSelectionChange">
  	<el-table-column align="center" width="80" type="selection"></el-table-column>
    <el-table-column align="center" width="130" label="资源ID" prop="id" show-overflow-tooltip></el-table-column>
    <el-table-column align="center" label="缩略图"  width="120" >
      <template slot-scope="scope">
        <div class="view-img-x" @click="watchSmPic(scope.$index, scope.row)">
          <img :src="scope.row.resUrl | setResUrl(scope.row.resType)" />      	
        </div>       
      </template>
    </el-table-column>
    <el-table-column align="center" label="资源名称" prop="resName" show-overflow-tooltip>
      <template slot-scope="scope">
        <el-input v-if="editNum === scope.$index" size="mini"  v-model="scope.row.resName"></el-input>
        <span v-else>{{scope.row.resName}}</span>
      </template>
    </el-table-column>
    <el-table-column align="center" label="类型" prop="resType"  width="110">
      <template slot-scope="scope">
        <template>{{ scope.row.resType | typeFilter }}</template>
      </template>
    </el-table-column>
    <el-table-column align="center" label="大小"  width="110">
      <template slot-scope="scope">
        {{ scope.row.resSize?scope.row.resSize:'---' }}
      </template>      
    </el-table-column>
    <el-table-column align="center" label="上传时间"  width="120" prop="created"  show-overflow-tooltip>
      <template slot-scope="scope">
        {{ scope.row.created | parseTime('{y}-{m}-{d}') }}
      </template>        
    </el-table-column>
    <el-table-column align="center" width="210"  label="操作">
      <el-button-group slot-scope="scope">	
        <el-button v-show="editNum !== scope.$index" type="primary" size="mini" @click.native.prevent="editWare(scope.row,scope.$index)">编辑</el-button>
        <el-button v-show="editNum === scope.$index" type="warning" size="mini" @click.native.prevent="editWare(scope.row,scope.$index)">确认</el-button>   
        <el-button type="primary" size="mini" @click.native.prevent="watchWare(scope.$index, scope.row)">详情</el-button>
        <el-button type="danger" size="mini"  @click.native.prevent="handleDel(scope.$index, scope.row)">删除</el-button> 
      </el-button-group>
    </el-table-column>              
  </el-table>
  <pagination v-show="total > listQuery.pageSize" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.pageSize" @pagination="getList"/>
  <upLoadResources v-model="upLoadFormVisible" @addResSuccess="addResSuccess"></upLoadResources>
	<groupResources v-model="groupVisible" @goToOne="goToOne" :groupNum="groupNum" ></groupResources>
	<editResources v-model="editVisible" @editSuccess="editSuccess" :editForm="editForm"></editResources>
  <el-image-viewer style="z-index:3000" v-if="showViewer" class="img-view" :on-close="()=>{showViewer=false}"  :url-list="srcList" />  
  <el-dialog title :visible.sync="videoVisible" class="video-dialog" :close-on-click-modal="false">	
    <i class="el-icon-circle-close video-close" @click="closeVideo"></i>
    <video v-if="videoType == '1'" ref="videoPlayer" controlsList="nodownload noremoteplayback" disablePictureInPicture οncοntextmenu="return false"  class="video-box" :src="videoUrl" controls></video>
    <video v-if="videoType == '2'" style="height:55px" ref="videoPlayer" controlsList="nodownload noremoteplayback" disablePictureInPicture οncοntextmenu="return false"  class="video-box" :src="videoUrl" controls></video>
  </el-dialog>
</div>
</template>
<script>
import config from '@/api/bgapi'
import request from '@/utils/request'
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination'
import upLoadResources from "./resources/upLoadResources"
import groupResources from "./resources/groupResources"
import editResources from "./resources/editResources"
import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
export default {
	components: {upLoadResources,ElImageViewer,Pagination,groupResources,editResources},	
  data() {
    return {
			upLoadFormVisible:false,
			loading: false,
			list:[],
			total:0,
			editNum:'',
      listQuery: {
        resName: '',
        page: this.$route.query.page?Number(this.$route.query.page):1,
        pageSize: 20
      },			
      uploadType:['image','video','audio'],
      typeName:['jpg/png/gif/jpeg','mp4','mp3/wma'],
      sizeName:[5,20,20],
			
			showViewer:false,
			srcList:[],
      videoVisible:false,
      videoUrl:'',
      videoType:'',
			
			groupVisible:false,
			groupNum:'',
			
			editVisible:false,
			editForm:{},				
		}
  },
	watch:{
		editVisible(newNum,oldNum){
			if(!newNum){
				this.editForm = {};
			}
		}
	},	
  mounted(){
    this.selectItme = [];
    this.getList();
  },
  methods: {
    async getList() {
      this.loading = true;
      var res = await request.get(config.resources,{params:this.listQuery});
      this.loading = false;
      this.list = res.data || [];
      this.total = res.totalNum || 0;
    },
    onSubmit(type) {		
			delete this.listQuery.id;
			this.listQuery.resName = type ? this.listQuery.resName : '';
      this.getList()
    },		
		async onChangeResUrl(data){
			var res = await request.put(config.resources+'/'+data.id,{resUrl:data.resUrl,resSize:data.resSize})
			if(res.code == '20000'){
				 this.$message.success('资源修改成功！')
				 this.getList();
			}			
		},
    async editWare(row,index){
			if(this.editNum === ''){
				this.editNum = index;
			}else{
				this.editNum = '';
				var res = await request.put(config.resources+'/'+row.id,{resName:this.list[index].resName})
			}
    },
		async watchSmPic(index, row){
			if(row.resType == '0'){
				this.showViewer = true;
				this.srcList =  [process.env.VUE_APP_BASE_API+row.resUrl];
			}else if(row.resType == '1' || row.resType == '2'){
        this.videoVisible = true;
        this.videoUrl = process.env.VUE_APP_BASE_API+row.resUrl; 
        this.videoType = row.resType;
        this.$nextTick(() => {
          this.$refs['videoPlayer'].play();
        })				
			}else if(row.resType == '3' || row.resType == '9'){
				this.editVisible = true;
				this.editForm = {...row};
			}else if(row.resType == '10'){
				//组合
				this.groupVisible = true;	
				this.groupNum = row.id;
			}
		},
		async watchWare(index, row){
			if(row.resType == '10'){
				//组合
				this.groupVisible = true;	
				this.groupNum = row.id;
			}else{
				this.editVisible = true;
				this.editForm = {...row};
			}
		},	
    handleDel(index, row){
      if (row.id) {
        this.$confirm("确认删除该记录吗?", "提示", {
            type: "warning",
        })
        .then(async () => {
            var res = await request.delete(config.resources+'/'+row.id);
            if(res.code == '20000'){
							if(res.type == 'del'){
								this.$message.success("删除成功");  
								this.getList();	
							}else{
								this.list = res.data || [];
								this.$message.error("该组合资源包含此资源，删除失败！");	
							}
            }
        })
        .catch(() => {
            this.$message.info("取消删除");
        });
      }
    },
		upLoadResources(){
      this.upLoadFormVisible = true;				
		},
		addResSuccess(){
			this.upLoadFormVisible = false;
			this.listQuery.page = 1;
			this.getList();				
		},
		editSuccess(){
			this.editVisible = false;
			this.getList();	
			this.$message.success('资源修改成功！')	
		},
    closeVideo(){
      this.videoType = '';
      this.videoVisible = false;
      this.videoUrl = '';
    },		
		handleSelectionChange(val){
			this.selectItme = val;
		},
		allDelItem(){
      if(this.selectItme.length == 0){return}
      this.$confirm("确认删除所选记录吗?", "提示", {
          type: "warning",
      })
      .then(async () => {
          let _ids = this.selectItme.map((item,index) =>{ return item.id});
          var res = await request.post(config.delManyRes,{ids:_ids});
          if(res.code == '20000'){
            this.$message.success("删除成功");  
            this.getList();	
          }
      })
      .catch(() => {
          this.$message.info("取消删除");
      });			
		},
		async groupWare(){
			if(this.selectItme.length > 10){this.$message.error('资源组合的个数必须不能大于10个！'); return}
			var _name = '';
			var _size = 0;
			var _hasGroup = false;
			let _ids = this.selectItme.map((item,index) =>{
				var _dd = this.selectItme.length == index + 1 ? '' : ',';	 
				_name += item.resName+_dd;
				_size += parseInt(item.resSize);
				if(item.resType == 10){_hasGroup = true}
				return item.id
			});
			if(_hasGroup){this.$message.error('资源组合里不能含有组合包！');return}
			var _data = {
        resType:10,
        resName:_name,
        resUrl:'',
				resContent:'',
				resSize:_size+'.00KB',
				resIds:_ids,				
			};
			var res = await request.post(config.resources,_data);
			if(res.code == '20000'){
				 this.$message.success('资源合并成功！')
				 this.getList();
			}			
		},
		goToOne(id){
			this.listQuery.id = id;
			this.groupVisible = false;
			this.getList()				
		},
	},
  filters: {
    typeFilter(status) {
      const typeMap = { 0: '图片', 1: '视频', 2: '音频', 3: '文字',9:'富文本',10:'组合' }
      return typeMap[status]
    },
		setResUrl(img,type){
			if(type == '0'){
				return process.env.VUE_APP_BASE_API+img;	
			}else if(type == '1'){
				return require('@/assets/images/video.png');	
			}else if(type == '2'){
				return require('@/assets/images/audio.png');	
			}else if(type == '3'){
				return require('@/assets/images/text.png');
			}else if(type == '9'){
				return require('@/assets/images/edit-text.png');
			}else if(type == '10'){
				return require('@/assets/images/group.png');
			}
		}
  },  
}
</script>
<style scoped>
.video-box{ width: 50%;}
.video-dialog >>> .el-dialog{width: 50%;  background:#F1F3F4; border-radius: 5px;}
.video-dialog >>> .el-dialog__header{ display: none;}
.video-dialog >>> .el-dialog__body{ width: 100%; height: 100%; padding: 0;}
.video-box{width: 100%; height: 100%; z-index: 88; border-radius: 5px; overflow: hidden; vertical-align: middle; outline: none; background:rgba(0, 0, 0, 0);}
.video-close{ font-size: 30px; z-index: 99;  position: absolute; top:-15px; right:-15px; cursor: pointer; background:#fff; border-radius: 30px;}

.img-view >>> .el-icon-circle-close {color: #5F6266; background: #fff; border-radius: 50%;}
.view-img{ vertical-align:middle; cursor:pointer; margin-left:10px;}
.view-img >>> .avatar-uploader{height:40px; margin:0; line-height:0; width:auto; max-width:80px; }
.view-img >>> .avatar-uploader .el-upload{border:1px solid #FAFAFA;border-radius:0;cursor: pointer;position: relative;overflow: hidden;}
.view-img >>> .avatar{ height:38px; max-width:78px;}
.view-img >>> .avatar-uploader .el-upload-dragger{ height:38px; max-width:78px; border:none;border-radius: 6px; display:flex;justify-content:center; align-items:center;}
.view-img-x{ cursor:pointer; vertical-align:middle; line-height:0;border:1px solid #FAFAFA; background:#fff;  height:40px;  margin:0 0 0 10px; line-height:0; width:auto; max-width:80px;}
.view-img-x >>> img{ max-width:100% !important; max-height:100%  !important;}
</style>